<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\customer\controller;


/**
 * 用户端聊天界面
 * @package app\customer\controller
 */
class Chat extends \think\Controller
{
    
    protected  $user_id = null;
    protected  $store_id = null;
    protected function initialize()
    {           
        config('app.dispatch_error_tmpl',  'customer@home/public/error');    
        $token = input("get.token");
        if (!$token) {
            $this->error('token 未定义',"");
        }
        if (!preg_match("/^[a-fA-F0-9]{32}$/", $token)) {
            $this->error('token 不正确',"");
        }
        $info = session($token);
        if(!$info){
           $this->error('token 不正确',""); 
        }
        $this->user_id = $info["user_id"] ?? 0;      
        $this->store_id = $info["store_id"] ?? 0;    
        if(!$this->user_id || !$this->store_id ){
            $this->error('token 不正确',""); 
        }
        $this->assign("jstoken",$token);
    }
    /**
     * 客服列表
     * @author 晓风<215628355@qq.com>
     * @return mixed
     */
    public function index()
    {
        //查询店铺     
        $store = \app\customer\model\Shop::where("store_id",$this->store_id )->find();
        if(!$store){
            $this->error("服务异常，出现不可预见的错误","");
        }   
        $user = \app\user\model\User::where("id",$this->user_id )->find();
        if(!$user){
            $this->error("服务异常，出现不可预见的错误","");
        }    
        //挂载商品或订单
        $goods_id = input("goods_id/d",0);
        $sku_id = input("sku_id/d",0);
        $order_sn = input("order_sn","");
        if($goods_id){
            $addinfo = \app\customer\model\Chat::getGoodsInfo($goods_id,$sku_id);
        }
        else if($order_sn){
            $addinfo= \app\customer\model\Chat::getOrderInfo($order_sn);
        }     
   
        $userSig = \app\customer\model\Chat::getUserSig($this->user_id);       
        $this->assign("userId",$this->user_id);
        $this->assign("store",$store);  
        $this->assign("user",$user);   
        $this->assign("userSig",$userSig);
        $this->assign("upToken", $this->request->token('osstoken'));
        $this->assign("addinfo",$addinfo);
        return $this->fetch();
    }
    
    public function get_user_messages(){
      
        $msgid = input("msgid","");        
        $store = \app\customer\model\Shop::field("store_name as user_nickname,store_logo as head_img")->where("store_id",$this->store_id)->find();
        if(!$store){
            $this->result([], 0, "店铺不存在", "json");
        }  
        $user = \app\user\model\User::field("user_nickname,head_img")->where("id",$this->user_id)->find();        
        if(!$user){
            $this->result([], 0, "会员不存在", "json");
        }  
    
        $store['head_img'] = get_file_url($store["head_img"]);
        $user['head_img'] = get_file_url($user["head_img"]);
        
        $userList = \app\customer\model\Chat::getUserStoreMsgList($this->user_id,$this->store_id,0 , $msgid);
        $info = [];
        
        foreach($userList as $item){
            $member = $item["form_type"]  == 2 ?  $store :$user;     
            $item['head_img'] = $member['head_img'];      
            $item['nickname'] =  $member['user_nickname'];                  
            $info[] = $item;
        }
        \app\customer\model\Session::clearSessionNoRead($this->user_id ,$this->store_id,1);
        $this->result($info, 1, "ok", "json");
    }
    
    public function check_client_user(){       
        $type = input("type/d",0);
        $content = input("content","");
        $session_title= input("session_title","");
        if(!$content){
            $this->result([], 0, "参数错误", "json");
        }      
        $user = \app\user\model\User::get($this->user_id);
        if(!$user){
            $this->result([], 0, "参数错误", "json");
        }
        \think\Db::startTrans();
        try{            
            $data['session_title'] = $data['session_title'] ??  "";
            $result = \app\customer\model\Chat::addUserMessageInfo($this->store_id,$this->user_id, $type,$content , $session_title);
            \think\Db::commit();            
        }catch(\Exception $e){
            \think\Db::rollback();
            $this->result(["err_code"=>$e->getCode()], 0, $e->getMessage(), "json");
        }       
        $message = [
            "msgid"=> $result['msgid'],    
            "type"=> $result['type'],      
            "content"=> $result['content'],   
            "user_id"=> $this->user_id,
            "store_id"=> $this->store_id, 
            "service_user_id"=> $result['service_user_id'],
            "nickname"=>  $user['user_nickname'],    
            "head_img"=>  get_file_url($user["head_img"]),           
            "form_type"=>$result['form_type'],   
            "create_time"=>date("Y-m-d H:i:s",$result["create_time"]),
            "session_title"=>$result['session_title'],
            "store_name"=>  $result['store_name'],    
            "store_logo"=>  get_file_url($result["store_logo"])
        ];
        //若离线
        if(!$result["service_user_id"]){
            $this->result($message, 2, "客服不在线，请稍候再咨询", "json"); 
        }
        $this->result($message, 1, "ok", "json");       
    } 
   
    /**
     * 问题匹配与搜索
     * @author 晓风<215628355@qq.com>
     */
    public function get_replay(){
        $type = input("type/d",0);
        $msg_type = input("msg_type/d",0);
        $content = input("content","");
        $session_title = input("session_title","");
        
        if($type == 1){
            $list = \app\customer\model\Reply::where("type",1)->field("problem,answer")->where("store_id","in",[0,$this->store_id])->limit(5)->order("id desc")->select();
            $this->result($list, 1, "ok", "json");
        }
        if($type == 2 &&  $msg_type == 0){          
            $keywords = $content;//这里要分词，留到后期升级,先这样吧 
            $list = \app\customer\model\Reply::where("type",2)->field("problem,answer")->where("problem","regexp",$keywords)->where("store_id","in",[0,$this->store_id])->limit(5)->order("id desc")->select();
            $this->result($list, 1, "ok", "json"); 
        }
       $this->result([], 1, "ok", "json");
    }
}